// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: gekim

#pragma once

#include <memory>
#include <string>

#include "coin2/base/string_util.h"
#include "coin2/exchange/base/symbology/currency.h"
#include "coin2/exchange/base/symbology/util.h"

namespace coin2::exchange::kucoin::symbology {

static const int64_t LUNA2_LIST_TIME = 1653609600000000000L;

class KucoinCurrency : public base::symbology::Currency,
                       public base::symbology::CurrencyFromStrMixin<KucoinCurrency> {
 public:
  using ExchangeType = base::market::ExchangeType;
  using MarketType = base::market::MarketType;
  using Currency = base::symbology::Currency;
  using base::symbology::Currency::native_currency;

 public:
  explicit KucoinCurrency(const std::string& currency)
      : Currency(currency, ToNativeCurrency(currency).value(), ExchangeType::Kucoin) {}

  static std::unique_ptr<KucoinCurrency> FromNativeStrImpl(
      const std::string& native_currency_str,
      int64_t resolve_timestamp) {
    auto currency = FromNativeCurrency(native_currency_str, resolve_timestamp);
    if (currency) {
      return std::make_unique<KucoinCurrency>(currency.value());
    }
    return {};
  }

  static std::unique_ptr<KucoinCurrency> FromNormStrImpl(
      const std::string& currency_str,
      int64_t resolve_timestamp) {
    return std::make_unique<KucoinCurrency>(currency_str);
  }

 private:
  static std::optional<std::string> ToNativeCurrency(const std::string& currency_str) {
    if (currency_str == "BCHSV") {
      return "BSV";
    } else if (currency_str == "BCHABC" || currency_str == "BCHN") {
      return "BCH";
    } else if (currency_str == "LUNA2") {
      return "LUNA";
    } else if (currency_str == "NANO") {
      return "XNO";
    }

    return currency_str;
  }

  static std::optional<std::string> FromNativeCurrency(
      const std::string& native_currency_str,
      int64_t resolve_timestamp) {
    if (native_currency_str == "BSV") {
      return "BCHSV";
    } else if (native_currency_str == "BCH") {
      if (resolve_timestamp >= base::symbology::BCHA_BCHN_FORK_TIME) {
        return "BCHN";
      } else {
        return "BCHABC";
      }
    } else if (native_currency_str == "LUNA" && resolve_timestamp >= LUNA2_LIST_TIME) {
      return "LUNA2";
    } else if (native_currency_str == "XNO") {
      return "NANO";
    }

    return native_currency_str;
  }
};

}  // namespace coin2::exchange::kucoin::symbology
